import uuid
from BloodSpiderAPI import models
from django import forms
from BloodSpiderAPI.apis.account import utils as account_utils
from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_first_error


# 记账表单
class AccountForm(forms.ModelForm):
    class Meta:
        model = models.Account
        fields = ['amount', 'category', 'description', 'a_type']  # 移除uid字段，确保不会通过表单更改所有者


# 创建记账记录
def create_account(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    # 从请求中获取数据
    data = request.POST.dict()
    
    # 检查必要参数
    if not data.get('uid') or not data.get('category'):
        return response_dict(message="用户ID和分类ID为必填项", code=1)
    
    try:
        # 验证外键存在
        user = models.User.objects.get(uid=data.get('uid'))
        category = models.Category.objects.get(cid=data.get('category'))
        
        # 创建表单实例（排除uid字段）
        form_data = data.copy()
        form = AccountForm(form_data)
        if not form.is_valid():
            return response_dict(data=get_first_error(form), code=1, message="参数错误")
        
        # 保存记账记录
        account = form.save(commit=False)
        account.aid = uuid.uuid4()
        # 直接设置外键对象，确保记账记录与用户正确关联
        account.uid = user
        account.category = category
        account.save()
        
        response = account_utils.utils_model_to_dict(account)
        return response_dict(data=response, message="记账记录创建成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.Category.DoesNotExist:
        return response_dict(message="分类不存在", code=1)
    except Exception as e:
        return response_dict(message=f"创建失败: {str(e)}", code=1)


# 获取记账记录列表
def get_account_list(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)
    
    # 获取查询参数
    uid = request.GET.get('uid')
    category_id = request.GET.get('category')
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    
    # 检查必要参数
    if not uid:
        return response_dict(message="用户ID为必填项", code=1)
    
    # 构建查询条件
    filters = {}
    if uid:
        try:
            user = models.User.objects.get(uid=uid)
            # 强制添加用户过滤条件，确保只能查询到当前用户的记账数据
            filters['uid'] = user
        except models.User.DoesNotExist:
            return response_dict(message="用户不存在", code=1)
    
    if category_id:
        try:
            category = models.Category.objects.get(cid=category_id)
            filters['category'] = category
        except models.Category.DoesNotExist:
            return response_dict(message="分类不存在", code=1)
    
    if start_time and end_time:
        filters['create_time__range'] = [start_time, end_time]
    
    # 查询数据
    accounts = models.Account.objects.filter(**filters).order_by('-create_time')
    
    # 转换为字典列表
    response_data = []
    for account in accounts:
        response_data.append(account_utils.utils_model_to_dict(account))
    
    return response_dict(data=response_data, message="获取成功")


# 获取记账记录详情
def get_account_detail(request, aid):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)
    
    # 获取请求用户ID
    user_id = request.GET.get('uid')
    if not user_id:
        return response_dict(message="用户ID为必填项", code=1)
    
    try:
        # 验证用户存在
        user = models.User.objects.get(uid=user_id)
        
        # 获取记账记录并验证所有权
        account = models.Account.objects.get(aid=aid, uid=user)
        response = account_utils.utils_model_to_dict(account)
        return response_dict(data=response, message="获取成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.Account.DoesNotExist:
        return response_dict(message="记账记录不存在或无权限访问", code=1)
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)


# 更新记账记录
def update_account(request, aid):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    # 从请求中获取数据
    data = request.POST.dict()
    
    # 检查必要参数
    user_id = data.get('uid')
    if not user_id:
        return response_dict(message="用户ID为必填项", code=1)
    
    try:
        # 验证用户存在
        user = models.User.objects.get(uid=user_id)
        
        # 获取记账记录并验证所有权
        account = models.Account.objects.get(aid=aid, uid=user)
        
        # 检查分类（如果提供）
        if data.get('category'):
            try:
                category = models.Category.objects.get(cid=data.get('category'))
            except models.Category.DoesNotExist:
                return response_dict(message="分类不存在", code=1)
        
        # 创建表单实例（排除uid字段，不允许更改所有者）
        form_data = data.copy()
        form = AccountForm(form_data, instance=account)
        if not form.is_valid():
            return response_dict(data=get_first_error(form), code=1, message="参数错误")
        
        # 保存更新后的记录
        updated_account = form.save(commit=False)
        # 只更新分类（如果提供），不允许更改所有者
        if data.get('category'):
            updated_account.category = category
        updated_account.save()
        
        response = account_utils.utils_model_to_dict(updated_account)
        return response_dict(data=response, message="更新成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.Account.DoesNotExist:
        return response_dict(message="记账记录不存在或无权限访问", code=1)
    except Exception as e:
        return response_dict(message=f"更新失败: {str(e)}", code=1)


# 删除记账记录
def delete_account(request, aid):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    # 从请求中获取数据
    data = request.POST.dict()
    
    # 检查必要参数
    user_id = data.get('uid')
    if not user_id:
        return response_dict(message="用户ID为必填项", code=1)
    
    try:
        # 验证用户存在
        user = models.User.objects.get(uid=user_id)
        
        # 获取记账记录并验证所有权
        account = models.Account.objects.get(aid=aid, uid=user)
        account.delete()
        return response_dict(message="删除成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.Account.DoesNotExist:
        return response_dict(message="记账记录不存在或无权限访问", code=1)
    except Exception as e:
        return response_dict(message=f"删除失败: {str(e)}", code=1)